package com.coolw.cola.statemachine.controller;

import com.coolw.cola.statemachine.dto.Order;
import com.coolw.cola.statemachine.enums.OrderEvent;
import com.coolw.cola.statemachine.enums.OrderStatusEnum;
import com.coolw.cola.statemachine.service.OrderService;
import com.coolw.common.api.BaseResult;
import org.dromara.hutool.core.data.id.IdUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 订单请求控制层
 *
 * @author coolw
 * @date 2024/4/9 14:13
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 场景1-用户关闭订单
     */
    @GetMapping("/close/user")
    public BaseResult<Void> userCloseOrder() {
        //Order order = buildOrder(OrderStatusEnum.WAITING_FOR_DELIVERY, "用户关闭");
        Order order = buildOrder(OrderStatusEnum.WAIT_PAYMENT, "用户关闭");
        orderService.close(order, OrderEvent.USER_CLOSE);
        return BaseResult.success();
    }

    /**
     * 场景2-管理员关闭订单
     */
    @GetMapping("/close/admin")
    public BaseResult<Void> adminCloseOrder() {
        Order order = buildOrder(OrderStatusEnum.WAIT_DELIVERY, "后台关闭");
        orderService.close(order, OrderEvent.ADMIN_CLOSE);
        return BaseResult.success();
    }

    /**
     * 场景3-超时关闭订单
     */
    @GetMapping("/close/overTime")
    public BaseResult<Void> overTimeCloseOrder() {
        Order order = buildOrder(OrderStatusEnum.WAIT_DELIVERY, "超时关闭");
        orderService.close(order, OrderEvent.OVERTIME_CLOSE);
        return BaseResult.success();
    }

    /**
     * 场景4-检查错误关闭订单
     */
    @GetMapping("/close/audit")
    public BaseResult<Void> checkErrorCloseOrder() {
        Order order = buildOrder(OrderStatusEnum.WAIT_DELIVERY, "审核关闭");
        orderService.close(order, OrderEvent.AUDIT_CLOSE);
        return BaseResult.success();
    }

    private Order buildOrder(OrderStatusEnum orderStatusEnum, String message) {
        return Order.builder()
                .orderId(IdUtil.getSnowflakeNextId())
                .orderStatus(orderStatusEnum)
                .message(message)
                .build();
    }
}
